package com.ash.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
import java.util.Properties;

/**
 * @author : Chen Chao
 * @encoding : UTF-8
 * @date : 2020/12/25 14:42
 * @file : test06.com.ash.util.ConnectionsUtil.java
 * @software : IntelliJ IDEA
 * @since : 1.8
 */
public class ConnectionsUtil {
    protected static String driver;
    protected static String url;
    protected static String user;
    protected static String password;
    protected static DruidDataSource ds;

    static {
        try (InputStream is = ConnectionsUtil.class.getClassLoader().
                getResourceAsStream("connection.properties");) {
            Properties properties = new Properties();
            properties.load(is);
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
            /*加载驱动*/
            Class.forName(driver);
            /*创建数据库连接池，加载配置文件*/
            ds = new DruidDataSource();
            ds.setDriverClassName(driver);
            ds.setUrl(url);
            ds.setUsername(user);
            /*注意不要写成name*/
            ds.setPassword(password);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取数据库连接池
     *
     * @return 数据库连接池
     */
    public static DruidDataSource getDataSource() {
        return ds;

    }

    /**
     * 获取数据库连接
     *
     * @return 返回数据库连接
     */
    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭数据库资源,Connection对象会回到连接池中
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
